package org.dromara.business.service.impl;

import org.dromara.business.domain.Video;
import org.dromara.business.mapper.VideoMapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.domain.BaseEntity;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.business.domain.bo.PlayHistoryBo;
import org.dromara.business.domain.vo.PlayHistoryVo;
import org.dromara.business.domain.PlayHistory;
import org.dromara.business.mapper.PlayHistoryMapper;
import org.dromara.business.service.IPlayHistoryService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 统一播放记录Service业务层处理
 *
 * @author Hao Tong Xue
 * @date 2025-04-21
 */
@RequiredArgsConstructor
@Service
public class PlayHistoryServiceImpl implements IPlayHistoryService {

    private final PlayHistoryMapper baseMapper;
    private final VideoMapper videoMapper;

    /**
     * 查询统一播放记录
     *
     * @param id 主键
     * @return 统一播放记录
     */
    @Override
    public PlayHistoryVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询统一播放记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 统一播放记录分页列表
     */
    @Override
    public TableDataInfo<PlayHistoryVo> queryPageList(PlayHistoryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PlayHistory> lqw = buildQueryWrapper(bo);
        Page<PlayHistoryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的统一播放记录列表
     *
     * @param bo 查询条件
     * @return 统一播放记录列表
     */
    @Override
    public List<PlayHistoryVo> queryList(PlayHistoryBo bo) {
        LambdaQueryWrapper<PlayHistory> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PlayHistory> buildQueryWrapper(PlayHistoryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PlayHistory> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(PlayHistory::getId);
        lqw.eq(bo.getContentId() != null, PlayHistory::getContentId, bo.getContentId());
        lqw.eq(bo.getContentType() != null, PlayHistory::getContentType, bo.getContentType());
        lqw.eq(bo.getPlayDuration() != null, PlayHistory::getPlayDuration, bo.getPlayDuration());
        lqw.eq(bo.getIsCompleted() != null, PlayHistory::getIsCompleted, bo.getIsCompleted());
        lqw.eq(bo.getWatchCount() != null, PlayHistory::getWatchCount, bo.getWatchCount());
        return lqw;
    }

    /**
     * 新增统一播放记录
     *
     * @param bo 统一播放记录
     */
    @Override
    public void insertByBo(PlayHistoryBo bo) {
        PlayHistory add = MapstructUtils.convert(bo, PlayHistory.class);
        validEntityBeforeSave(add);

        PlayHistory playHistory = baseMapper.selectOne(
            Wrappers.<PlayHistory>lambdaQuery()
                .eq(PlayHistory::getContentId, add.getContentId())
                .eq(BaseEntity::getCreateBy, LoginHelper.getUserId())
                .eq(PlayHistory::getContentType, add.getContentType())
        );

        if (playHistory == null) {

            if (bo.getContentType() == 1) { // video
                Video video = videoMapper.selectById(add.getContentId());
                video.setPlayCount(video.getPlayCount() + 1);
                videoMapper.updateById(video);
            }
            baseMapper.insert(add);
        }else {

            add.setId(playHistory.getId());

            if (playHistory.getIsCompleted() == 1) {
                add.setWatchCount(playHistory.getWatchCount() + 1);
            }

            baseMapper.updateById(add);

        }

    }

    /**
     * 修改统一播放记录
     *
     * @param bo 统一播放记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(PlayHistoryBo bo) {
        PlayHistory update = MapstructUtils.convert(bo, PlayHistory.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PlayHistory entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除统一播放记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 通过内容id获取统一播放记录详细信息
     *
     * @param contentId 内容id
     * @param contentType 主键 内容类型：1-视频，2-音频
     * @return 统一播放记录
     */
    @Override
    public PlayHistoryVo getInfo(Long contentId, Integer contentType) {
        return baseMapper.selectVoOne(Wrappers.<PlayHistory>lambdaQuery().eq(PlayHistory::getContentId, contentId).eq(PlayHistory::getContentType, contentType).eq(BaseEntity::getCreateBy, LoginHelper.getUserId()));
    }
}
